import axios from "axios";
import {ElMessage} from 'element-plus'
import router from "@/router";

// 请求拦截器
axios.interceptors.request.use(config => {
    // 如果存在token，则后续请求携带此token
    if (window.sessionStorage.getItem('tokenStr')) {
        config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr');
    }
    return config;
}, error => {
    console.log(error);
})


// 响应拦截器
axios.interceptors.response.use(success => {
    // 业务逻辑错误
    // 状态码为200表示请求成功
    if (success.status && success.status === 200) {
        // 这里对服务器端定义的错误进行拦截，打印服务器返回的错误信息
        if (success.data.code === 500 || success.data.code === 401 || success.data.code === 403) {
            ElMessage({message: success.data.message, type: 'error', center: true});
            return;
        }
        // 这里表示请求成功后，服务器也成功响应，如果有返回信息，则打印成功的信息
        if (success.data.message) {
            ElMessage({message: success.data.message, type: 'success', center: true});
        }
        return success.data;
    }
}, error => {
    if (error.response.code === 504 || error.res.code === 404) {
        ElMessage({message: '服务器好像坏掉了，待会再试试吧 (～￣▽￣)～', type: 'error', center: true});
    } else if (error.response.code === 403) {
        ElMessage({message: '权限不足，请联系管理员', type: 'error', center: true});
    } else if (error.response.code === 401) {
        ElMessage({message: '尚未登录，请登录再试', type: 'error', center: true});
        router.replace('/login').then(() => 'to login');
    } else {
        if (error.response.message) {
            ElMessage({message: error.response.message, type: 'error', center: true});
        } else {
            ElMessage({message: '出现未知错误，请联系管理员!', type: 'error', center: true});
        }
    }
});

const baseUrl = '';
// 传送JSON格式的POST请求
export const postRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.post(`${baseUrl}${url}`, params).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err)
        })
    })
}
// GET请求
export const getRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.get(`${baseUrl}${url}`, {
            params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

// 传送json格式的put请求
export const putRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.put(`${baseUrl}${url}`, params).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        })
    })
}

// delete请求
export const deleteRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.delete(`${baseUrl}${url}`, {
            params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
